import React, { useRef, useState } from 'react';
import {
  Animated,
  PanResponder,
  TouchableOpacity,
  View,
  Text,
  StyleSheet,
  Dimensions,
  Easing,
  Platform
} from 'react-native';

const { width: screenWidth, height: screenHeight } = Dimensions.get('window');

const FloatButton = ({
  onPress = () => {},
  icon = '+',
  size = 60,
  color = '#5E7CE2',
  glowColor = 'rgba(94, 124, 226, 0.5)',
  textColor = '#C3E4FF',
  initialPosition = { right: 30, bottom: 100 }
}) => {
  // 计算初始位置
  const initialX = screenWidth - initialPosition.right - size;
  const initialY = screenHeight - initialPosition.bottom - size;
  
  const pan = useRef(new Animated.ValueXY({ 
    x: initialX, 
    y: initialY 
  })).current;
  const [isDragging, setIsDragging] = useState(false);
  const scale = useRef(new Animated.Value(1)).current;

  // 边界吸附动画
  const snapToEdge = (dx, dy) => {
    let newX = dx;
    let newY = dy;
    
    // 水平边界判断
    if (dx < screenWidth / 2 - size / 2) {
      newX = 20; // 吸附到左边缘
    } else {
      newX = screenWidth - size - 20; // 吸附到右边缘
    }
    
    // 垂直边界限制（不超出屏幕）
    newY = Math.max(40, Math.min(newY, screenHeight - size - 40));

    Animated.parallel([
      Animated.spring(pan, {
        toValue: { x: newX, y: newY },
        useNativeDriver: false,
      }),
      Animated.timing(scale, {
        toValue: 1,
        duration: 200,
        easing: Easing.elastic(1),
        useNativeDriver: true,
      })
    ]).start();
  };

  // 拖拽手势处理
  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onPanResponderGrant: () => {
        setIsDragging(true);
        Animated.spring(scale, {
          toValue: 1.2,
          useNativeDriver: true,
        }).start();
      },
      onPanResponderMove: Animated.event(
        [null, { dx: pan.x, dy: pan.y }],
        { useNativeDriver: true }
      ),
      onPanResponderRelease: (_, { dx, dy, vx, vy }) => {
        setIsDragging(true);
        snapToEdge(dx, dy);
      },
    })
  ).current;

  // 按钮点击动画
  const handlePress = () => {
    if (isDragging) return;
    
    Animated.sequence([
      Animated.timing(scale, {
        toValue: 0.9,
        duration: 100,
        useNativeDriver: true,
      }),
      Animated.spring(scale, {
        toValue: 1,
        friction: 3,
        useNativeDriver: true,
      })
    ]).start(() => onPress());
  };

  return (
    <Animated.View
      style={[
        styles.container,
        {
          width: size,
          height: size,
          borderRadius: size / 2,
          backgroundColor: color,
          transform: [
            { translateX: pan.x },
            { translateY: pan.y },
            { scale: scale },
          ],
        },
      ]}
      {...panResponder.panHandlers}
    >
      <TouchableOpacity
        activeOpacity={0.7}
        onPress={handlePress}
        style={[styles.button, { borderRadius: size / 2 }]}
      >
        {/* 发光效果层 */}
        {!isDragging && (
          <Animated.View 
            style={[
              styles.glow, 
              { 
                borderRadius: size / 2,
                backgroundColor: glowColor,
              }
            ]} 
          />
        )}
        
        {/* 按钮内容 */}
        <Text style={[styles.text, { color: textColor, fontSize: size * 0.4 }]}>
          {icon}
        </Text>
      </TouchableOpacity>
    </Animated.View>
  );
};

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    zIndex: 9999,
    ...Platform.select({
      ios: {
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 4 },
        shadowOpacity: 0.3,
        shadowRadius: 8,
      },
      android: {
        elevation: 10,
      },
    }),
  },
  button: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    overflow: 'hidden',
  },
  glow: {
    position: 'absolute',
    width: '100%',
    height: '100%',
    opacity: 0.8,
  },
  text: {
    fontWeight: 'bold',
    textAlign: 'center',
    textShadowColor: 'rgba(0, 245, 212, 0.5)',
    textShadowOffset: { width: 0, height: 0 },
    textShadowRadius: 8,
  },
});

export default FloatButton;